/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import MyLib.ShowCenterScreen;
import Object.Torrent;
import XML.DOMUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import sun.awt.WindowClosingSupport;

/**
 *
 * @author QuangHau
 */
public class Setting extends javax.swing.JDialog {

    /**
     * Creates new form Setting
     */
    public ArrayList<String> listID = new ArrayList<String>();
    public Setting(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
//        ArrayList<String> lstIpAdd = new ArrayList<>();
//        lstIpAdd.add("192.168.1.1");
//        lstIpAdd.add("192.168.1.2");
//        lstIpAdd.add("192.168.1.3");
//        writeMap(lstIpAdd);
        tbNetWork.setModel(readMap());
        tbFile.setModel(readFile());
        ShowCenterScreen.show(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbNetWork = new javax.swing.JTable();
        btnCancel = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbFile = new javax.swing.JTable();
        btnDeleteFile = new javax.swing.JButton();
        btnCancelFile = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Netword list"));

        tbNetWork.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STT", "IP Address"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tbNetWork);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
        );

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(5, 5, 5))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnAdd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnDelete)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnCancel)
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnCancel, btnDelete});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnAdd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(20, 20, 20))
        );

        jTabbedPane2.addTab("Network", jPanel1);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "File list"));

        tbFile.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STT", "Name", "Size", "Chunk"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tbFile);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
        );

        btnDeleteFile.setText("Delete");
        btnDeleteFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteFileActionPerformed(evt);
            }
        });

        btnCancelFile.setText("Cancel");
        btnCancelFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelFileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(5, 5, 5))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnDeleteFile)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnCancelFile)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDeleteFile)
                    .addComponent(btnCancelFile))
                .addGap(20, 20, 20))
        );

        jTabbedPane2.addTab("File", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jTabbedPane2))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jTabbedPane2)
                .addGap(0, 0, 0))
        );

        jTabbedPane2.getAccessibleContext().setAccessibleName("tab2");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        //ObjectInputStream ois;
        addNetWork f = new addNetWork(null, true);
        ShowCenterScreen.show(f);
        f.setVisible(true);
        ObjectInputStream ois;
        try {
            ois = new ObjectInputStream(new FileInputStream("network.map"));
            int num = (int) ois.readObject();
            ArrayList<String> lstIpAdd = new ArrayList<>();
            for (int i = 0; i < num; i++) {
                lstIpAdd.add((String) ois.readObject());
            }
            if (f.IpAdd != null) {
                lstIpAdd.add(f.IpAdd);
            }
            writeMap(lstIpAdd);
            tbNetWork.setModel(readMap());
            ois.close();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Setting.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Setting.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        ObjectInputStream ois;
        try {
            if (tbNetWork.getRowCount() > 0) {
                // TODO add your handling code here:
                int postion = tbNetWork.getSelectedRow();
                if (!(postion < 0)) {
                    ois = new ObjectInputStream(new FileInputStream("network.map"));
                    int num = (int) ois.readObject();
                    ArrayList<String> lstIpAdd = new ArrayList<>();
                    for (int i = 0; i < num; i++) {
                        lstIpAdd.add((String) ois.readObject());
                    }
                    lstIpAdd.remove(postion);
                    writeMap(lstIpAdd);
                    tbNetWork.setModel(readMap());
                    ois.close();
                }
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Setting.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Setting.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnCancelFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelFileActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelFileActionPerformed

    private void btnDeleteFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteFileActionPerformed
        // TODO add your handling code here:
        try {
            if (tbFile.getRowCount() > 0) {
                // TODO add your handling code here:
                int postion = tbFile.getSelectedRow();
                if (!(postion < 0)) 
                {
                    String idFile = listID.get(postion) ;
                    Document document = DOMUtil.parse("Data.xml");
                    NodeList listFile = document.getDocumentElement().getChildNodes();
                    Path defaultPath = Paths.get(Paths.get("").toAbsolutePath().toString()+"\\Data");
                    
                    for (int i = 0; i < listFile.getLength(); i++) {
                        Node nodeFile = listFile.item(i);
                        if (nodeFile.getNodeName().equals("File") && nodeFile.getAttributes().getNamedItem("id").getNodeValue().equals(idFile)) 
                        {
                            document.getDocumentElement().removeChild(nodeFile);
                            DOMUtil.writeXmlToFile("Data.xml", document);
                            listID.remove(postion);
                            tbFile.setModel(readFile());
                            //xoa file trong thu muc
                            Delete_File(defaultPath, idFile);
                            System.out.println("delete file " + idFile);
                        }
                    }
                }
            }

        } catch (Exception e) {
        }
    }//GEN-LAST:event_btnDeleteFileActionPerformed

    /**
     * @param args the command line arguments
     */
    public void Delete_File(Path currentPath,String nameFileDel) throws IOException
    {
        File fileDel  = new File(currentPath.toString() + "\\" + nameFileDel);
        if(fileDel.isDirectory())
        {
            //thu muc trong
            if(fileDel.list().length == 0)
            {
                fileDel.delete();
                System.out.println("Xoa thanh cong!!!");
                return;
            }
            
            String[] subFile = fileDel.list();
            for(String temp : subFile)
            {
                
                File file = new File(fileDel.getPath());
                Delete_File(Paths.get(fileDel.getPath()),temp);
            }
            if(fileDel.list().length == 0)
            {
                fileDel.delete();
                System.out.println("Xoa thanh cong!!!");
                return;
            }
        }
        else if(fileDel.exists())
        {
            fileDel.delete();
            System.out.println("Xoa thanh cong!!!");
            return;
        }
        System.out.println("Co loi xay ra!!!----Huy xoa file!!!");
       
        return;
        

    }
    
    public DefaultTableModel readFile() {
        DefaultTableModel dtm = new DefaultTableModel() {
            public boolean isCellEditable(int rowIndex, int mColIndex) {
                return false;
            }
        };
        try {
            Vector data_rows;
            Vector column_name = new Vector();
            column_name.addElement("STT");
            column_name.addElement("Name");
            column_name.addElement("Size(Kb)");
            column_name.addElement("Chunk");
            
            
            dtm.setColumnIdentifiers(column_name);
            Document document = DOMUtil.parse("Data.xml");
            NodeList listFile = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < listFile.getLength(); i++) {
                Node nodeFile = listFile.item(i);
                if (nodeFile.getNodeName().equals("File")) {
                    data_rows = new Vector();
                    data_rows.addElement(String.valueOf(i + 1));
                    data_rows.addElement(nodeFile.getAttributes().getNamedItem("name").getNodeValue());
                    data_rows.addElement(nodeFile.getAttributes().getNamedItem("size").getNodeValue());
                    data_rows.addElement(nodeFile.getAttributes().getNamedItem("chunk").getNodeValue());
                    dtm.addRow(data_rows);
                    listID.add(nodeFile.getAttributes().getNamedItem("id").getNodeValue());
                }
            }
        } catch (Exception e) {
        }
//        dtm.getColumnExt(4).setVisible(false);
        return dtm;
    }

    public DefaultTableModel readMap() {
        DefaultTableModel dtm = new DefaultTableModel() {
            public boolean isCellEditable(int rowIndex, int mColIndex) {
                return false;
            }
        };
        try {
            Vector data_rows;
            Vector column_name = new Vector();
            column_name.addElement("STT");
            column_name.addElement("IP Address");
            dtm.setColumnIdentifiers(column_name);

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("network.map"));
            int num = (int) ois.readObject();

            for (int i = 1; i <= num; i++) {
                data_rows = new Vector();
                data_rows.addElement(String.valueOf(i));
                data_rows.addElement((String) ois.readObject());
                dtm.addRow(data_rows);
            }

            ois.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Setting.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Setting.class.getName()).log(Level.SEVERE, null, ex);
        }
        return dtm;
    }

    private void writeMap(ArrayList<String> lstIpAdrr) {
        ObjectOutputStream outStream;
        try {
            outStream = new ObjectOutputStream(new FileOutputStream("network.map"));
            outStream.writeObject(lstIpAdrr.size());//id
            for (int i = 0; i < lstIpAdrr.size(); i++) {
                outStream.writeObject(lstIpAdrr.get(i));//ip
            }
            outStream.close();
        } catch (IOException ex) {
            Logger.getLogger(Torrent.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }


        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Setting dialog = new Setting(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnCancelFile;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnDeleteFile;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTable tbFile;
    private javax.swing.JTable tbNetWork;
    // End of variables declaration//GEN-END:variables
}
